package com.tuotu.gps;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.clam314.lame.MediaPlayUtil;
import com.clam314.lame.MediaRecorderButton;
import com.tuotu.gps.adapter.MyRecycleViewAdapter;
import com.tuotu.gps.entity.LocationInfo;
import com.tuotu.gps.entity.MessageEvent;
import com.tuotu.gps.utils.CollectionFile;
import com.tuotu.gps.utils.GpsLocationUtils;
import com.tuotu.gps.utils.LogUtil;
import com.tuotu.gps.utils.Preference;
import com.tuotu.gps.utils.Utils;
import com.tuotu.gps.view.FreeDialog;
import com.tuotu.gps.view.ItemActionDialog;
import com.tuotu.gps.view.MenuDialog;
import com.tuotu.gps.view.MyDialogInterface;
import com.tuotu.gps.view.RecordStatusDialog;
import com.tuotu.gps.view.SelfAlertDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RecordActivity2 extends AppCompatActivity implements MyRecycleViewAdapter.onClickListener, GpsLocationUtils.setStatusListener {

    SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");//设置日期格式
    SimpleDateFormat dirFormat = new SimpleDateFormat("yyyy_MM_dd");//设置日期格式
    //    public final String GPS_DIR="/mnt/sdcard/gps/";
    public static String GPS_DIR = Environment.getExternalStorageDirectory().getPath() + "/gps/";
    public static String GPS_UPLOAD_DIR = Environment.getExternalStorageDirectory().getPath() + "/gpsUpload/";
    public static String GPS_DIR_TODAY;
    public String GPS_PATH;

    private static final int MSG_REFRESH_UI_TIME = 5000; //间隔5s刷新一次listview
    private static final int MSG_REFRESH_LOCATION_TIME = 1000; //每秒刷新左上角定位
    private static final int MSG_SAVE_FILE_TIME = 1000 * 60 * 5; //5分钟保存一个轨迹点
    private static final int MSG_REFRESH_UI = 0;
    private static final int MSG_REFRESH_LOCATION = 1;
    private static final int MSG_SAVE_FILE = 2;
    private static final int MSG_UPLOAD_MP3_FILE = 5;

    @BindView(R.id.recycleview)
    RecyclerView mRecycleView;
    @BindView(R.id.record)
    MediaRecorderButton mRecord;

    @BindView(R.id.tv_data)
    TextView mGpsStatus;
    @BindViews({R.id.tv_lon, R.id.tv_lat})
    TextView[] gpsTvs;

    @BindView(R.id.recording)
    TextView recording;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;

    private MyRecycleViewAdapter adapter;
    private List<LocationInfo> list;
    private CollectionFile mCollectionFile;
    SharedPreferences preferences;
    SharedPreferences userPreferences;
    MyHandler myHandler;
    GpsLocationUtils gpsLocationUtils;
    Location mLocation;
    double lon, lat;
    int checkCount;
    private AlertDialog dialog;
    private long lastTime;
    private Animation bottomMenuIn;
    private Animation bottomMenuout;
    Dialog recordMotionDialog;
    RecordStatusDialog mRecordStatusDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record2);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        LogUtil.createLogFile();
        createGpsDirectory();
        applyPremission();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initStatusDilaog();
        init();
        changeQueryData();
        initRecycleView();
        setUserId();
        RecordViewEvent();

        initVolume();//把音量调成最大
//        bottomMenuIn = AnimationUtils.loadAnimation(this, R.anim.slide_in_left);
//        bottomMenuout = AnimationUtils.loadAnimation(this, R.anim.slide_out_right);
        LogUtil.print("RecordActivity onCreate");
    }

    private void initStatusDilaog() {
        mRecordStatusDialog = new RecordStatusDialog(this);
        mRecordStatusDialog.setmOnStatusStopListener(new RecordStatusDialog.OnStatusStopListener() {
            @Override
            public void onStatusRecordStop() {
                mRecord.recordStart(0);
            }
        });
    }

    private void initVolume() {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setStreamVolume(AudioManager.STREAM_MUSIC,
                am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
    }

    @Override
    public void onBackPressed() {
        long nowTime = System.currentTimeMillis();
        if ((nowTime - lastTime) > 1000) {
            LogUtil.toast(this, "双击退出");
            lastTime = nowTime;
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_user_delete://注销用户名
                showUserLogoutDialog();
                break;
            case R.id.uploadFileAction:
                SelfAlertDialog dialog2 = new SelfAlertDialog(this);
                dialog2.setTitle("确定上传");
                dialog2.setYesButton(new SelfAlertDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick(SelfAlertDialog dialog) {
                        dialog.cancel();
                        Intent intent = new Intent(RecordActivity2.this, UploadActivity2.class);
                        intent.putExtra("needUpload", true);
                        startActivity(intent);
                    }
                });
                dialog2.setNoButton(new SelfAlertDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick(SelfAlertDialog dialog) {
                        dialog.cancel();
                    }
                });
//                dialog2.setCancelable(true);
//                dialog2.setCanceledOnTouchOutside(true);
                dialog2.show();
                break;
            case R.id.uploadFilelist:
                Intent intent = new Intent(RecordActivity2.this, UploadActivity2.class);
                intent.putExtra("needUpload", false);
                startActivity(intent);
                break;
        }

//        return super.onOptionsItemSelected(item);
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (intent.getBooleanExtra("needResume", false)) {
            mCollectionFile = new CollectionFile(this, GPS_PATH);
            list.clear();
            if (null != adapter)
                adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void setUserId() {
        userPreferences = getSharedPreferences(Preference.User.PREFERENCE_USER, MODE_PRIVATE);
        String name = userPreferences.getString(Preference.User.PREFERENCE_USER_NAME, "");
        LogUtil.print("RecordActivity onCreate name==" + name);
        if (name.equalsIgnoreCase("") || null == name) {
            final EditText editText = new EditText(this);
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
            AlertDialog dialog = new AlertDialog.Builder(this).setTitle("请输入电话号码").
                    setView(editText).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String text = editText.getText().toString();
                            LogUtil.print("RecordActivity onCreate text" + text);
                            if (text == null || text.equalsIgnoreCase("")) {
                                LogUtil.toast(getApplicationContext(), "用户名不能为空");
                                finish();
                            } else {
                                userPreferences.edit().putString(Preference.User.PREFERENCE_USER_NAME, text).commit();
//                                    tvUsername.setText(text);
                            }
                        }
                    }).create();
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
//        dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
            dialog.show();
        } else {
//            tvUsername.setText(name);
        }

    }

    private void applyPremission() {
        //判断当前系统是否高于或等于6.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            LogUtil.print("Build.VERSION.SDK_INT --" + Build.VERSION.SDK_INT);
            //当前系统大于等于6.0
            if (ActivityCompat.checkSelfPermission(RecordActivity2.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(RecordActivity2.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(RecordActivity2.this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(RecordActivity2.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(RecordActivity2.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    ) {
            } else {
                LogUtil.print("need applyPremission");
                //不具有权限，需要进行权限申请
                ActivityCompat.requestPermissions(RecordActivity2.this, new String[]{
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, 124);
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        LogUtil.print("onRequestPermissionsResult requestcode==" + requestCode);
        switch (requestCode) {
            case 124:
                LogUtil.print("onRequestPermissionsResult permissions==" + permissions[0] + "---" + permissions[1]);
                LogUtil.print("onRequestPermissionsResult grantResults==" + grantResults[0] + "---" + grantResults[1]);

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void changeQueryData() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                radioGroup.check(i);
                switch (i) {
                    case R.id.checkbox_today:
                        setGPS_PATH(GPS_DIR + dirFormat.format(new Date()) + "/");
                        break;
//                    case R.id.rb1:
//                        Calendar calendar=Calendar.getInstance();
//                        setGPS_PATH(GPS_DIR+dirFormat.format(new Date(calendar.getTime().getTime()-1000*60*60*24))+"/");
//                        break;
//                    case R.id.rb2:
//                        Calendar calendar2=Calendar.getInstance();
//                        setGPS_PATH(GPS_DIR+dirFormat.format(new Date(calendar2.getTime().getTime()-1000*60*60*24*2))+"/");
//                        break;
                    case R.id.checkbox_all:
                        setGPS_PATH(GPS_DIR);
                        break;
                }
                LogUtil.print("GPS_PATH--" + getGPS_PATH());
                mCollectionFile = new CollectionFile(RecordActivity2.this, GPS_PATH);
            }
        });
    }

    public String getGPS_PATH() {
        return GPS_PATH;
    }

    public void setGPS_PATH(String GPS_PATH) {
        this.GPS_PATH = GPS_PATH;
    }

    private void initRecycleView() {
        list = mCollectionFile.getList();
        LogUtil.print("RecordActivity list.size==" + list.size());
        if (null == adapter) {
            adapter = new MyRecycleViewAdapter(this, list, preferences);
            adapter.setList(list, GPS_PATH);
            mRecycleView.setAdapter(adapter);
            adapter.setOnClickListener(this);
        } else {
            adapter.setList(list, GPS_PATH);
            adapter.notifyDataSetChanged();
        }
        if (null != list && list.size() > 0) {
            mRecord.setBastPath(list.get(adapter.getSelectedPosition()).getMp3PathName());
        }
        mRecycleView.scrollToPosition(adapter.getItemCount() - 1);
        if(null!=list && list.size()>0)
            adapter.setSelectedPosition(list.size()-1);
    }

    private void init() {
        gpsLocationUtils = GpsLocationUtils.getInstance(getApplicationContext());
        gpsLocationUtils.onStatusListener(this);
        gpsLocationUtils.beginUpdateLocation();
        preferences = getSharedPreferences(Preference.gpsTimeLong.PREFERENCE_NAME, MODE_PRIVATE);
//        LogUtil.print("preference size=="+preferences.getAll().size());
        preferences.edit().clear().commit();
//        LogUtil.print("after remove preference size=="+preferences.getAll().size());

        myHandler = new MyHandler(this);
        myHandler.sendEmptyMessage(MSG_REFRESH_UI);
        myHandler.sendEmptyMessage(MSG_REFRESH_LOCATION);
        myHandler.sendEmptyMessage(MSG_SAVE_FILE);

        mRecycleView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        mCollectionFile = new CollectionFile(RecordActivity2.this, GPS_PATH);
    }

    /**
     * 创建一个GPS的文件夹，测试的时候放在内置sd卡下，正式放在sd卡下
     */
    private void createGpsDirectory() {
        userPreferences = getSharedPreferences(Preference.User.PREFERENCE_USER, MODE_PRIVATE);
        String name = userPreferences.getString(Preference.User.PREFERENCE_USER_NAME, "");
        GPS_DIR = GPS_DIR + name + "/";
        GPS_UPLOAD_DIR = GPS_UPLOAD_DIR + name + "/";
        GPS_DIR_TODAY = GPS_DIR + dirFormat.format(new Date()) + "/";
        GPS_PATH = GPS_DIR + dirFormat.format(new Date()) + "/";
        LogUtil.printE("RecordActivity createGpsDirectory name==" + name);
        LogUtil.printE("RecordActivity createGpsDirectory GPS_DIR==" + GPS_DIR);
        LogUtil.printE("RecordActivity createGpsDirectory GPS_UPLOAD_DIR==" + GPS_UPLOAD_DIR);
        LogUtil.printE("RecordActivity createGpsDirectory GPS_DIR_TODAY==" + GPS_DIR_TODAY);
        LogUtil.printE("RecordActivity createGpsDirectory GPS_PATH==" + GPS_PATH);
        File dirFile = new File(GPS_PATH);
        if (!dirFile.exists()) {
            LogUtil.print("createGpsDirectory--" + GPS_PATH);
            dirFile.mkdirs();
            LogUtil.print("createGpsDirectory-- success");
        }
        File SuccessFile = new File(GPS_UPLOAD_DIR + "success/");
        if (!SuccessFile.exists()) {
            LogUtil.print("SuccessFile--" + GPS_UPLOAD_DIR + "success/");
            SuccessFile.mkdirs();
            LogUtil.print("SuccessFile-- success");
        }
        File failFile = new File(GPS_UPLOAD_DIR + "fail/");
        if (!failFile.exists()) {
            LogUtil.print("failFile--" + GPS_UPLOAD_DIR + "fail/");
            failFile.mkdirs();
            LogUtil.print("failFile-- success");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MainRun(MessageEvent event) {
        if (event.what == MessageEvent.MSG_FILE_COLLECTIION_DONE) {
            initRecycleView();
        }
    }

    private void RecordViewEvent() {
        mRecord.setGpsLocationUtils(gpsLocationUtils);
        mRecord.setRecorderStatusListener(new MediaRecorderButton.RecorderStatusListener() {
            @Override
            public void beforeStart() {
                mRecordStatusDialog.setViewVisibility(1);
//                recording.setText("正在录音...");
//                recording.setVisibility(View.VISIBLE);
//                startVoice();
            }

            @Override
            public void onStart(int status, String mp3Name, Date date, int typeRecord) {
                mRecordStatusDialog.setTypeRecord(typeRecord);
                mRecordStatusDialog.show();
                recordStartRecord(mp3Name, date, typeRecord);
//                startVoice();
            }

            @Override
            public void onEnd(int status) {
                //status除了是状态还有录音的秒数
                switch (status) {
                    case MediaRecorderButton.END_RECORDER_TOO_SHORT:
                        mRecordStatusDialog.dismiss();
                        Toast.makeText(RecordActivity2.this, "讲话时间太短啦！", Toast.LENGTH_SHORT).show();
                        break;
//                    case 10:
//                        Toast.makeText(RecordActivity.this,"录音50秒啦，10秒后自动发送",Toast.LENGTH_SHORT).show();
//                        break;
                    case MediaRecorderButton.END_RECORDER_60S:
                        mRecordStatusDialog.dismiss();
                        Toast.makeText(RecordActivity2.this, "录音超过60S,自动暂停", Toast.LENGTH_SHORT).show();
                        recordStopRecord();
                        break;
                    case MediaRecorderButton.END_RECORDER_CANCEL:
//                        LogUtil.printE("record onEnd==="+MediaRecorderButton.END_RECORDER_CANCEL);
                        mRecordStatusDialog.dismiss();
                        recordStopRecord();
                        break;
                }
            }

            @Override
            public void noLocation() {
                LogUtil.toast(RecordActivity2.this, "未定位不能录音");
            }
        });
        mRecord.setFinishListener(new MediaRecorderButton.RecorderFinishListener() {
            @Override
            public void onRecorderFinish(int status, String mp3FilePath, String second, int typeRecord) {
                LogUtil.printE("record onRecorderFinish===" + status + "--second==" + second + "--typeRecord==" + typeRecord);
                int index = mp3FilePath.lastIndexOf(".");//"."最后出现的位置
                String name = mp3FilePath.substring(0, index);
                String content = Utils.readFile(name + ".txt");
                if (TextUtils.isEmpty(content)) {
                    return;
                }
                JSONObject jsonObject = null;
                FileWriter fileWriter = null;
                int beforeDuration = 0;
                try {
                    jsonObject = new JSONObject(content);
                    if (typeRecord == 1){
//                        beforeDuration = jsonObject.getInt("mp3_duration");//补充之前的录音
                        beforeDuration =Integer.parseInt(Utils.getFromBase64(jsonObject.getString("mp3_duration")));//补充之前的录音
                    }
                    LogUtil.printE("record onRecorderFinish= beforeDuration==" + beforeDuration);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    int allSecond=Integer.parseInt(second) + beforeDuration;
                    jsonObject.put("mp3_duration", Utils.getBase64(String.valueOf(allSecond)));
//                    jsonObject.put("mp3_duration", (Integer.parseInt(second) + beforeDuration));
                    fileWriter = new FileWriter(name + ".txt");
                    fileWriter.write(jsonObject.toString());
                    fileWriter.flush();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != fileWriter)
                            fileWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void recordStartRecord(String mp3Name, Date date, int typeRecord) {
        LogUtil.print("start audioStartRecord");
        gpsLocationUtils.setNeedUploadPath(true);
        mLocation = gpsLocationUtils.getLastLocation();
        if (null == mLocation) {
//            recording.setText("未定位\n 正在录音");
//            return;
        } else {
//            recording.setText("准备录音");
        }
//        recording.setVisibility(View.VISIBLE);
        /**重要
         * typeRecord==0表示第一次录音，1 补充录音 2重新录音   1、2不需要创建gps点文件
         */
        if (typeRecord!=0) {

            return;
        }

        if (null != mLocation) {
            //有定位，保存并上传轨迹点
            GPS_DIR_TODAY = GPS_DIR + dirFormat.format(date) + "/";
            Utils.createGpsFile(mLocation.getLongitude(), mLocation.getLatitude(), mLocation.getBearing()
                    , GPS_DIR_TODAY + mp3Name, date.getTime());
//            HttpNetworkUtil.httpPostPoint(this,
//                    userPreferences.getString(Preference.User.PREFERENCE_USER_NAME,""),mp3Name
//            ,mLocation.getLongitude(),mLocation.getLatitude(),mLocation.getBearing(),GPS_PATH+mp3Name);
        }

//        SharedPreferences.Editor editor=preferences.edit();
//        editor.putLong(mp3Name+".mp3",date.getTime()).commit();
    }

    private void recordStopRecord() {
//        recording.setVisibility(View.GONE);
        if (null != adapter) {
            mCollectionFile = new CollectionFile(RecordActivity2.this, GPS_PATH);
            adapter.setSelectedPosition(adapter.getSelectedPosition());
        }

//        myHandler.sendEmptyMessageDelayed(MSG_UPLOAD_MP3_FILE,5000);//5S之后上传MP3文件

    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void backRun(MessageEvent event) {
        if (event.what == MessageEvent.MSG_PLAY_NOTIFICATION) {
//            startVoice();
        }
    }

    @OnClick({R.id.record, R.id.tv_data,R.id.main_tv_menu,R.id.main_tv_help})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_tv_help:
                Intent intent=new Intent(RecordActivity2.this,UserHelpActivity.class);
                startActivity(intent);
                break;
            case R.id.main_tv_menu:
                showMenuDialog();
                break;
            case R.id.record:
                break;
            case R.id.tv_data:
                break;
        }
    }

    private void showMenuDialog() {
        MenuDialog pMenuDialog=new MenuDialog(this);
        pMenuDialog.setmMenuActionListener(new MenuDialog.onMenuActionListener() {
            @Override
            public void menuUploadData() {
                Intent intent = new Intent(RecordActivity2.this, UploadActivity2.class);
                intent.putExtra("needUpload", true);
                startActivity(intent);
            }

            @Override
            public void menuCheckData() {
                Intent intent = new Intent(RecordActivity2.this, UploadActivity2.class);
                intent.putExtra("needUpload", false);
                startActivity(intent);
            }

            @Override
            public void menuDeleteNoUploadData() {
                list.clear();
                adapter.notifyDataSetChanged();
                Utils.deleteAllNOUploadFile(GPS_DIR);
            }

            @Override
            public void menuUserLogout() {
                showUserLogoutDialog();
            }
        });
        pMenuDialog.show();
    }

    private void showUserLogoutDialog(){
        String name = userPreferences.getString(Preference.User.PREFERENCE_USER_NAME, "");
        SelfAlertDialog dialog1 = new SelfAlertDialog(this);
        dialog1.setTitle("是否注销用户\n" + name);
        dialog1.setYesButton(new SelfAlertDialog.onYesOnclickListener() {
            @Override
            public void onYesClick(SelfAlertDialog dialog) {
                userPreferences.edit().clear().commit();
                Intent intent = new Intent(RecordActivity2.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
        dialog1.setNoButton(new SelfAlertDialog.onNoOnclickListener() {
            @Override
            public void onNoClick(SelfAlertDialog dialog) {
                dialog.cancel();
            }
        });
//                dialog1.setCancelable(true);
//                dialog1.setCanceledOnTouchOutside(true);
        dialog1.show();
    }

    /**
     * 删除选定的MP3
     */
    private void deleteRecordMP3() {
        MediaPlayUtil.release();
        deleteMp3File(adapter.getSelectedPosition());
//        dialog.cancel();
//        MediaPlayUtil.release();
//        SelfAlertDialog dialog1 = new SelfAlertDialog(this);
//        dialog1.setTitle("是否删除？");
//        dialog1.setYesButton(new SelfAlertDialog.onYesOnclickListener() {
//            @Override
//            public void onYesClick(SelfAlertDialog dialog) {
//                deleteMp3File(adapter.getSelectedPosition());
//                dialog.cancel();
//            }
//        });
//        dialog1.setNoButton(new SelfAlertDialog.onNoOnclickListener() {
//            @Override
//            public void onNoClick(SelfAlertDialog dialog) {
//                dialog.cancel();
//            }
//        });
////        dialog1.setCancelable(false);
////        dialog1.setCanceledOnTouchOutside(false);
//        dialog1.show();
    }

    /**
     * 重新录音
     */
    private void coverRecordMP3() {
        MediaPlayUtil.release();
        mRecord.recordStart(2);
//        SelfAlertDialog dialog1 = new SelfAlertDialog(this);
//        dialog1.setTitle("是否重新录音");
//        dialog1.setYesButton(new SelfAlertDialog.onYesOnclickListener() {
//            @Override
//            public void onYesClick(SelfAlertDialog dialog) {
//                mRecord.recordStart(2);
//                dialog.cancel();
//            }
//        });
//        dialog1.setNoButton(new SelfAlertDialog.onNoOnclickListener() {
//            @Override
//            public void onNoClick(SelfAlertDialog dialog) {
//                dialog.cancel();
//            }
//        });
////        dialog1.setCancelable(false);
////        dialog1.setCanceledOnTouchOutside(false);
//        dialog1.show();
    }


    @Override
    public void onItemClick(final View view, int position) {
        if (mRecord.isSelected()) {
            LogUtil.toast(this, "请先停止录音");
            return;
        }

        if(view.getId()==R.id.ib_play){
            if(position==adapter.getSelectedPosition() && MediaPlayUtil.isPlaying()){
                MediaPlayUtil.release();
                LogUtil.printE("停止播放");
            }else {
                MediaPlayUtil.release();
                MediaPlayUtil.init(this);
                MediaPlayUtil.playSound(list.get(position).getMp3PathName(), new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        MediaPlayUtil.release();
                        ((ToggleButton) view).setChecked(false);
                    }
                });
            }
        }else {
            MediaPlayUtil.release();
        }

        mRecord.setBastPath(list.get(position).getMp3PathName());
        adapter.setSelectedPosition(position);
        adapter.notifyDataSetChanged();

        if(view.getId()==R.id.ib_play){
            return;
        }

        itemActionDialogInit();
//        recordMotionDialogAction();//打开录音操作窗口
        /*
            case R.id.tv_direction:
                Intent txtIntent = new Intent(Intent.ACTION_VIEW);
                txtIntent.setDataAndType(Uri.parse("file://" +list.get(position).getTxtPathName()), "text/plain");
                LogUtil.print("txtname=="+GPS_PATH +list.get(position)+".txt");
                startActivity(txtIntent);
                break;
        }
        */
    }

    private void itemActionDialogInit() {
        ItemActionDialog dialog = new ItemActionDialog(this,adapter.getSelectedPosition(),list.get(adapter.getSelectedPosition()));
        dialog.setmItemDialogListener(new ItemActionDialog.itemDialogListener() {
            @Override
            public void itemVoicePlay() {
                MediaPlayUtil.release();
                palyVoiceFile(list.get(adapter.getSelectedPosition()).getMp3PathName());
            }

            @Override
            public void itemVoiceAdd() {
                MediaPlayUtil.release();
                mRecord.recordStart(1);
            }

            @Override
            public void itemVoiceDeleteConfirm() {
                deleteRecordMP3();
            }

            @Override
            public void itemVoiceCoverConfirm() {
                coverRecordMP3();
            }
        });
        dialog.show();
    }


    private void recordMotionDialogAction() {
        if (null == recordMotionDialog) {
            recordMotionDialog = new Dialog(this, R.style.recordMotionDialogStyle);
        }
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_layout, null);
        TextView mp3Info = dialogView.findViewById(R.id.select_mp3_info);
        String name = list.get(adapter.getSelectedPosition()).getMp3Name();
        String str = name.substring(11, name.length() - 4).replace("_", ":");
        mp3Info.setText(str);
        dialogView.findViewById(R.id.dialog_tv_play).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                palyVoiceFile(list.get(adapter.getSelectedPosition()).getMp3PathName());
                recordMotionDialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.dialog_tv_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRecord.recordStart(1);
                recordMotionDialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.dialog_tv_cover).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                coverRecordMP3();
                recordMotionDialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.dialog_tv_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteRecordMP3();
                recordMotionDialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.dialog_tv_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recordMotionDialog.dismiss();
            }
        });
        recordMotionDialog.setContentView(dialogView);
        recordMotionDialog.show();
//        recordMotionDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        recordMotionDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onItemLongClick(View view, final int position) {
        LogUtil.print("onItemLongClick");
        /*
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("您可以执行以下操作").
                setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        MediaPlayUtil.release();
                        recording.setVisibility(View.GONE);
                    }
                }).setNegativeButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MediaPlayUtil.release();
                recording.setVisibility(View.GONE);
                deleteMp3File(position);
            }
        }).setNeutralButton("播放", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                palyVoiceFile(list.get(adapter.getSelectedPosition()).getMp3PathName());
            }
        })
        .create().show();
        */
    }

    @Override
    protected void onDestroy() {
        gpsLocationUtils.saveFile(userPreferences.getString(Preference.User.PREFERENCE_USER_NAME, "xyw"));
        gpsLocationUtils.stopUpdateLocation();
        myHandler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);
        UploadService.isUploading = false;
        super.onDestroy();
        GPS_DIR = Environment.getExternalStorageDirectory().getPath() + "/gps/";
        GPS_UPLOAD_DIR = Environment.getExternalStorageDirectory().getPath() + "/gpsUpload/";
        System.gc();
        Log.e("xyww", "RecordActivity onDestroy");
    }

    private void deleteMp3File(final int position) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String tmpName = list.get(position).getMp3PathName();//获取全名,如fire.mp3
                int index = tmpName.lastIndexOf(".");//"."最后出现的位置
                String name = tmpName.substring(0, index);
                Utils.deleteFile(name);
                list.remove(position);
                adapter.setList(list, GPS_PATH);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    private void showDialog() {
        if (null == dialog)
            dialog = new AlertDialog.Builder(this).
                    setMessage("已经2分钟没有GPS更新啦").create();
        hideDialog();
        dialog.show();
    }

    private void hideDialog() {
        if (null != dialog) {
            dialog.dismiss();
        }
    }

    @Override
    public void setGpsCount(int count) {

    }

    @Override
    public void showChangedialog() {
        showChangeGpsDialog();
    }

    private void showChangeGpsDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this,R.style.baseDialog).setTitle("需要去打开GPS确定位置，请选择仅限设备").
                setPositiveButton("去打开", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Intent intent = new Intent();
                            intent.setAction("android.settings.LOCATION_SOURCE_SETTINGS");
                            startActivity(intent);
                        } catch (Exception e) {

                        }
                    }
                }).create();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
//        dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        dialog.show();
    }

    private void palyVoiceFile(String path) {
        LogUtil.print("play name=" + path);
        MediaPlayUtil.release();
        MediaPlayUtil.init(this);
//        recording.setText("正在播放");
//        recording.setVisibility(View.VISIBLE);
        MediaPlayUtil.playSound(path, new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                MediaPlayUtil.release();
//                recording.setText("播放完成");
//                recording.setVisibility(View.GONE);
                if(null!=adapter)
                    adapter.notifyDataSetChanged();
            }
        });
        if(null!=adapter)
            adapter.notifyDataSetChanged();
    }

    private static class MyHandler extends Handler {

        private final WeakReference<RecordActivity2> reference;

        public MyHandler(RecordActivity2 activity) {
            reference = new WeakReference<RecordActivity2>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            RecordActivity2 mActivity = reference.get();
            if (null != mActivity) {
                switch (msg.what) {
                    case MSG_REFRESH_UI:
                        if (null != mActivity.adapter) {
                            mActivity.adapter.notifyDataSetChanged();
                        }

                        sendEmptyMessageDelayed(MSG_REFRESH_UI, MSG_REFRESH_UI_TIME);

                        break;
                    case MSG_REFRESH_LOCATION:
                        mActivity.mLocation = mActivity.gpsLocationUtils.getLastLocation();
                        if (null != mActivity.mLocation) {
//                            mActivity.mGpsStatus.setText(mActivity.mLocation.getLongitude()+"\n"+mActivity.mLocation.getLatitude()
//                                    +"=="+mActivity.gpsLocationUtils.getSatelliteCount());
                            mActivity.mGpsStatus.setText(mActivity.getResources().getString(R.string.GPS_success));
                            mActivity.mGpsStatus.setTextColor(Color.parseColor("#58E704"));
                            mActivity.gpsTvs[0].setText("E:" + (int)(mActivity.mLocation.getLongitude()*100000)/(float)100000.0);
                            mActivity.gpsTvs[1].setText("N:" + (int)(mActivity.mLocation.getLatitude()*100000)/(float)100000.0);
//                            mActivity.gpsTvs[2].setText("有效卫星:"+mActivity.gpsLocationUtils.getSatelliteCount());
                            if (mActivity.mLocation.getLongitude() == mActivity.lon && mActivity.mLocation.getLatitude() == mActivity.lat) {
                                mActivity.checkCount++;
                            } else {
                                mActivity.checkCount = 0;
                                if(null!=mActivity.dialog && mActivity.dialog.isShowing()){
                                    mActivity.hideDialog();
                                }
                            }
                            if (mActivity.checkCount == 120) {
                                mActivity.checkCount = 0;
                                LogUtil.print("no gps point change after 120s");
                                mActivity.mGpsStatus.setText(mActivity.getResources().getString(R.string.GPS_fail));
                                mActivity.mGpsStatus.setTextColor(Color.parseColor("#ff0000"));
                                mActivity.showDialog();
                                LogUtil.print("mGpsStatus=="+ mActivity.mGpsStatus.getText());
                            }
                            mActivity.lon = mActivity.mLocation.getLongitude();
                            mActivity.lat = mActivity.mLocation.getLatitude();
                        }
                        sendEmptyMessageDelayed(MSG_REFRESH_LOCATION, MSG_REFRESH_LOCATION_TIME);
                        break;
                    case MSG_SAVE_FILE:
                        mActivity.gpsLocationUtils.saveFile(
                                mActivity.userPreferences.getString(Preference.User.PREFERENCE_USER_NAME, "xyw")
                        );
                        sendEmptyMessageDelayed(MSG_SAVE_FILE, MSG_SAVE_FILE_TIME);
                        break;
                    case MSG_UPLOAD_MP3_FILE:
//                        HttpNetworkUtil.httpPostMp3(mActivity,mActivity.userPreferences.getString(Preference.User.PREFERENCE_USER_NAME,"xyw")
//                                , new File(mActivity.GPS_DIR_TODAY+mActivity.mp3Name+".mp3")
//                        );
                        break;
                }
            }
        }
    }
}
